<?php

namespace App\Http\Controllers\Api;

use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class TaskController extends BaseController
{
    /**
     * 获取备忘信息
     */
    public function lists(Request $request) {
        try {
            $items = Task::where('user_id', $request->user->id)->get();
            foreach ($items as $key => $val) {
                $items[$key]->status_title = Task::$_status_title[$val->status];
            }
            return $this->response(200, '获取成功', $items);
        } catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
    /**
     * 修改状态
     */
    public function modify(Request  $request) {
        try {
            $task_id = $request->input('task_id', 0);
            $task = Task::find($task_id);
            if (empty($task)) return $this->response(400, '任务不存在或者task_id参数错误');
            $status = 1;
            if ($task->status == 1) $status = 2;
            if (!Task::where('id', $task_id)->update(['status' => $status])) {
                return $this->response(400, '修改失败');
            }
            return $this->response(200, '修改成功');
        } catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
    /**
     * 删除
     */
    public function delete(Request $request) {
        try {
            $task_id = $request->input('task_id', 0);
            if (!Task::where('id', $task_id)->delete()) {
                return $this->response(400, '删除失败');
            }
            return $this->response(200, '修改成功');
        } catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
    /**
     * 创建任务
     */
    public function add(Request $request) {
        try {
            $title = $request->input('title','');
            if (empty($title)) return $this->response(400, '请填写标题');
            $complete_date = $request->input('complete_date', '');
            if (empty($complete_date)) return $this->response(400, '请填写完成日期');
            $data = [
                'user_id' => $request->user->id,
                'title' => $title,
                'complete_date' => $complete_date
            ];
            if (!Task::create($data)) {
                return $this->response(400, '创建失败');
            }
            return $this->response(200, '创建成功');
        } catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }

    public function upload(Request $request) {
        try {
            $path = $request->file('sign_name')->store('uploads/images');
            $url = url($path);
            return $this->response(200, '上传成功', ['path' => $path, 'url' => $url]);
        } catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
}
